import { action, observable } from "mobx";
import { typeOf } from "stl-typescript";

export class IState<T> {
  readonly name: string;
  @observable current: T | T[];
  origin: any;
  readonly isObject: boolean;
  readonly isArray: boolean;
  constructor(name: string, initialValue: T) {
    this.name = name;
    this.isObject = typeOf(initialValue) === "Object";
    this.isArray = typeOf(initialValue) === "Array";
    this.current = initialValue;
    if (this.isObject && !this.isArray) {
      this.origin = { ...initialValue };
    } else if (this.isArray && !this.isObject) {
      this.origin = [];
    } else {
      this.origin = initialValue;
    }
  }

  @action
  setValue(value: T) {
    this.current = value;
  }

  reset() {
    if (this.isObject && !this.isArray) {
      this.current = { ...this.origin };
    } else if (this.isArray && !this.isObject) {
      this.current = [];
    } else {
      this.current = this.origin;
    }
  }
}
